﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.Core.DBUtility;
using Microhard.Core.Algorithm;
using Microhard.Framework.MVCHelper;

namespace Microhard.Permission.MVCFilter
{
    public class BeforeCreateActionFilter : IActionDataFilter
    {

        #region IActionFilter Members

        public bool FilterAction(System.Web.Mvc.ActionExecutingContext filterContext, Models.User currentUser, List<Models.Permission> currentPermissions, Core.DBUtility.ScopeResult dataScope)
        {
            var toaddModel = filterContext.ActionParameters["model"];
            if (toaddModel != null)
            {
                //给主键设置ID
                var pkid = AlgCompare.GetPKID<ModelPKIDAttribute>(toaddModel);
                if (pkid == Guid.Empty)
                {
                    AlgCompare.SetPKIDPropertyValue(ref toaddModel, Guid.NewGuid());
                }
            }
            BasePermissionModel bpm = toaddModel as BasePermissionModel;
            if (bpm != null)
            {
                //有可能对于一个资源有相同的权限（Scope不同），所以，这里只用取第一个即可
                bpm.OperatorID = currentUser.ID;
                bpm.CurrentPermissionID = currentPermissions.First().PermissionID;
                bpm.CurrentPermissionResourceID = currentPermissions.First().ResID;
                bpm.CurrentPermissionResourceName = currentPermissions.First().ResourceName;
                bpm.CurrentLoginUserName = currentUser.UserName;
                //设置操作状态
                bpm.OperationStatus = OperationStatus.Add;
            }

            filterContext.ActionParameters["model"] = toaddModel;
            return true;
        }

        public Guid PKID
        {
            get;
            set;
        }
        #endregion


        public bool IsAdminAction
        {
            set;
            get;
        }
    }
}
